package com.jingdianjichi.club.gateway.filter;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author 董代恒
 * @version 1.0
 */
@Component
@Slf4j
public class LoginFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest.Builder mutate = request.mutate();
        String url = request.getURI().getPath();
        log.info("LoginFilter.filter.url:{}", url);
        if (url.equals("/user/doLogin")) {
            return chain.filter(exchange);
        }

        //这个soTaken框架的知识，用这个api可以获取到登录的token?
        /*
            [tokenName=satoken, tokenValue=cZvlwdhQiAa9REWncNsap3YwtXuHpUzJ, isLogin=true,
            loginId=oAxu-6E5mC77wLcDV6YxJRc4kdYg, loginType=login, tokenTimeout=2591818, sessionTimeout=2591817,
            tokenSessionTimeout=-2, tokenActiveTimeout=-1, loginDevice=default-device, tag=null]
         */
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();

        log.info("LoginFilter.filter.tokenInfo:{}", tokenInfo);

        String loginId = (String) tokenInfo.getLoginId();

        mutate.header("loginId", loginId);

        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }
}
